<template>
  <!--毕业设计相关打印弹框-->
  <div class="design-print">
    <edu-dialog :title="actionType === 'ADD' ? $t('graduationDesign.add') : $t('graduationDesign.edit')" width="50%" @close="onCancel" :visible="dialogVisible">
      <el-form :model="designPrintForm" ref="designPrintForm" :rules="designPrintRules" label-position="right" label-suffix="：" label-width="150px">
        <el-row>
          <el-col>
            <el-form-item prop="attachPath">
              <el-upload ref="upload" :data="{bucketname: 'face', folderpath: 'file'}" :file-list="fileList" :on-success="uploadSuccess" :action="importUrl" :multiple="false" :on-change="(file, fileList)=>{ this.fileList = fileList}" :limit="1" accept=".doc, .docx, .xlsx, .xls, .pdf" :before-upload="beforeUpload" :on-error="handleError" :on-exceed="handleExceed" :on-progress="handleUpload" :on-remove="handleRemove">
                <el-button slot="trigger" size="small" type="primary" icon="el-icon-upload" v-loading.fullscreen.lock="loading" element-loading-text="Loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, .48)">{{$t('graduationDesign.selectFile')}}</el-button>
                <div slot="tip" class="el-upload__tip">{{$t('graduationDesign.designPrintUploadFileTips')}}</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="buttons">
        <el-button @click="onCancel">{{$t('graduationDesign.cancel')}}</el-button>
        <el-button type="primary" @click="onSubmit">{{$t('graduationDesign.confirm')}}</el-button>
      </div>
    </edu-dialog>
  </div>
</template>
<script>
import API from "common/src/api/underGraduationDesign/graduationDesign";

export default {
  name: 'stuInfoDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    designPrintForm: {
      type: Object,
      default: {
        attachName: '',
        attachPath: ''
      }
    },
    actionType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      api: API,
      designPrintRules: {
        attachPath: [
          { required: true, message: this.$t('graduationDesign.pleaseUploadFile'), trigger: 'change' }
        ]
      },
      importUrl: '/api/commonservice/obsfile/uploadfile',
      fileList: [],
      actionMode: 'NEXT',
      loading: false,
      deletedFilePath: '', // 待删除的文件路径
      attachDeleteStatus: false
    };
  },
  mounted() {
    if (this.actionType === "EDIT") {
      this.deletedFilePath = this.designPrintForm.attachPath;
      this.attachDeleteStatus = false;
      this.fileList = [{
        name: this.designPrintForm.attachName,
        url: this.designPrintForm.attachPath
      }];
    }
  },
  methods: {
    onCancel() {
      this.$emit("design-print-cancel");
    },
    handleUpload(event, file, fileList) {
      this.loading = true;
    },
    deleteFileFromObs(path) {
      return this.api.deleteFile(path).then(res => {
        return res;
      });
    },
    // 确定
    onSubmit() {
      this.$refs.designPrintForm.validate(async (valid) => {
        if (valid) {
          // 上传的原文件被修改，则提交的时候删除obs库中的原文件，只保留一个最新的文件
          if (this.actionType === "EDIT" && this.attachDeleteStatus) {
            await this.deleteFileFromObs(this.deletedFilePath);
          }
          this.$emit("design-print-submit", this.designPrintForm, this.actionType);
        } else {
          return false;
        }
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(this.$t('graduationDesign.onlyOneFileCanBeUpload'));
    },
    // 清除文件
    clearFiles() {
      this.$refs.upload.clearFiles();
      this.fileList = [];
    },
    //上传校验
    beforeUpload(file) {
      const fileType = file.name.replace(/.+\./, "");
      const isSize = file.size / (1024 * 1024 * 20) < 1;
      const isFile = ['doc', 'docx', 'xls', 'xlsx', 'pdf'].includes(fileType.toLowerCase());
      if (!isFile) {
        this.$message.error(this.$t('graduationDesign.designPrintUploadFileTypeMsg'));
        this.clearFiles();
      }
      if (!isSize) {
        this.$message.error(this.$t('graduationDesign.designPrintUploadFileSizeMsg'));
        this.clearFiles();
      }
      if (!(isSize && isFile)) {
        this.loading = false;
      }
      return isSize && isFile;
    },
    // 手动上传
    uploadFile() {
      if (_.isEmpty(this.fileList)) {
        this.$message.warning(this.$t('message.selectFilePlease'));
        return;
      }
      this.loading = true;
      this.$refs.upload.submit();
    },
    // 上传成功
    uploadSuccess(res, file, fileList) {
      this.loading = false;
      if (res.code == 200) {
        this.designPrintForm.attachName = res.data[file.name].fileName;
        this.designPrintForm.attachPath = res.data[file.name].objectkey;
        this.$message.success(this.$t('graduationDesign.uploadSuccess'));
        this.$refs.designPrintForm.clearValidate();
      }
    },
    async handleRemove(file, fileList) {
      if (this.designPrintForm.attachPath) {
        // 编辑时第一次修改了原文件，则删除状态标记为true
        if (this.actionType === "EDIT" && this.deletedFilePath === this.designPrintForm.attachPath) {
          this.attachDeleteStatus = true;
        } else {
          await this.deleteFileFromObs(this.designPrintForm.attachPath);
        }
        this.$message.success(this.$t('graduationDesign.deleteSuccess'));
        this.designPrintForm.attachName = "";
        this.designPrintForm.attachPath = "";
        this.$refs.designPrintForm.clearValidate();
      }
    },
    handleError(err, file, fileList) {
      this.loading = false;
      this.$message.error(err.message);
    }
  }
}
</script>
<style lang="scss" scoped>
.design-print {
    .design-print-input {
        width: 100%;
    }
}
</style>
